<template>
  <div class="cart-box">
    <!--空车-->
    <template v-if="productData.length<1">
      <div class="is-empty-box">
        <img src="../../assets/images/cart_empty.png" alt="">
        <router-link to="/shop">
          <p>去逛逛</p>
        </router-link>
      </div>
    </template>
    <!--非空车-->
    <template v-if="!isEmpty">
      <ul class="no-empty-box">
        <li :key="index" v-for="(item,index) in productData">
          <div class="fl-left">
            <div style="display: inline-block" @click="isSelected(index)">
              <img v-if="!item.status" class="status-img" src="../../assets/images/select.png" alt="">
              <img v-if="item.status" class="status-img" src="../../assets/images/selected.png" alt="">
            </div>
            <router-link to="">
              <img class="product-img" :src="sourceUrl+item.goods.goodsImg" alt="">
            </router-link>
          </div>
          <div class="fl-right">
            <p class="title-name">{{item.goods.goodsName}}</p>
            <p class="discription clamp2">{{item.goods.goodsBrief}}</p>
            <div class="price-box">
              <div class="pb-left">
                <span>￥{{item.goods.shopPrice}}</span>
              </div>
              <div class="pb-right">
                <img src="../../assets/images/minus_icon.png" alt="" @click="minusNum(index)">
                <input :id="'buynum'+index" type="number" v-model.number="item.num" @change="changedValue(index)"/>
                <img src="../../assets/images/add_icon.png" alt="" @click="addNum(index)"/>
              </div>
            </div>
          </div>
        </li>
      </ul>
      <textPop v-if="showPop" :textPop="textTip"></textPop>
      <div class="footer" v-if="productData.length>0">
        <div class="f-all" @click="toggleAll()">
          <img v-if="!selecteAll" src="../../assets/images/select.png" alt="">
          <img v-if="selecteAll" src="../../assets/images/selected.png" alt="">
          <span>全选</span>
        </div>
        <div class="f-delete" @click="deleteSelected()">
          <span>删除</span>
        </div>
        <div class="f-selttlement" @click="settlement()">
          <span>结算</span>
        </div>
      </div>
    </template>
    <!--底部footer-->
    <Footer tabNum="2"></Footer>
  </div>

</template>

<script>
  import global from '../public/global.vue'
  export default {
    name: 'cartIndex',
    data() {
      return {
        isEmpty: false,//购物车是否为空
        productData: [], //产品数据
        selecteAll: false, //是否全选
        showPop: false,//是否选择弹窗
        textTip: "",//弹窗提示内容
        sourceUrl:global.sourceUrl,
        flag:[],
      }
    },
    methods: {
      //数量加
      addNum(idx) {
        let numLen = this.productData;
        for (let i = 0; i < numLen.length; i++) {
          if (numLen[idx].num < 10) { //小于库存数量禁止再加
            if (idx == i) {
              numLen[idx].num++;
            }
          }
        }
      },
      //数量减
      minusNum(idx) {
        let numLen = this.productData;
        for (let i = 0; i < numLen.length; i++) {
          if (numLen[idx].num > 1) {
            if (idx == i) {
              numLen[idx].num--;
            }
          }
        }
      },

      //监听buynum变化
      changedValue(idx) {
        this.productData.sum = document.getElementById('buynum' + idx).value;
      },
      //单选
      isSelected(idx) {
        console.log(idx)
        this.productData[idx].status = !this.productData[idx].status;
        let pData = this.productData;
        let flag1=[];
        pData.forEach((val, i) => {
          if (val.status) {
            flag1.push(true);
          } else {
            flag1.push(false);
          }
        })

        if (flag1.indexOf(false) > -1) {
          this.selecteAll = false;
        } else {
          this.selecteAll = true;
        }
        this.flag=flag1;
      },
      //全选
      toggleAll() {
        this.selecteAll = !this.selecteAll;

        let flag1=[];
        let pData = this.productData;
        pData.forEach((val, i) => {
          val.status = this.selecteAll;
          flag1.push(true);
        })
        this.flag=flag1;
        let st=false;
        if(this.selecteAll){
           st=true
        }
        for(let n=0;n<this.flag.length;n++){
          this.flag[n]=st;
        }

        console.log(this.flag);
      },
      //删除
      deleteSelected() {
        let pData = this.productData;
        console.log(pData);
        let ids = new Array();
        for (let i = 0; i < pData.length; i++) {
          if (pData[i].status) {
            ids.push(pData[i].id)
            pData.splice(i, 1);
            i -= 1;
          }
        }
        if (pData.length < 1) {
          this.selecteAll = false;
          this.isEmpty = true;
        } else {
          this.isEmpty = false;
        }
        let params = new URLSearchParams();
        params.append("ids",ids);
        this.$http({
          url: global.apiUrl + '/shoppingCart/shoppingCartDelete',
          method: 'post',
          data: params,
        }).then(res => {
          console.log(res);
          setTimeout(() => {

          }, 1000)
        }).catch(function (err) {
          console.error(err);
        });

      },
      //结算
      settlement() {

        let pData = this.productData;
        let shoppingCartListId = [];
        let totalMoney = '';
        let prods=new Array();
        pData.forEach((val, i) => {
          if (val.status) {
            totalMoney += val.price;
          }
          if(this.flag[i]){
            prods.push(pData[i]);

          }
        })
        if (!totalMoney) {
          this.showPop = true;
          this.textTip = "请选择结算商品";
          setTimeout(() => {
            this.showPop = false;
          }, 1000)
        } else {
          this.showPop = false;
          this.textTip = "";
          let orderProducts=new Array();

          prods.forEach((val, i) => {
            let products=new Object();
            shoppingCartListId.push(prods[i].id)
            products.goodsId=prods[i].goodsId;
            products.goodsName=prods[i].goods.goodsName;
            products.price = prods[i].goods.shopPrice;
            products.orderNumber = prods[i].num;
            products.fee = products.price*products.orderNumber;
            orderProducts.push(products);
          })
          window.localStorage.setItem("prods", JSON.stringify(orderProducts));
          this.$router.push({
            name: 'buyNow',
            params: {
              type: "car",
              shoppingCartListId:shoppingCartListId
            }
          })
        }
        console.log(prods);

      }

    },
    created: function () {
      document.title = "购物车";
      var uid = this.$route.query.uid;
      if (uid != undefined) {
        window.localStorage.setItem("shareId",uid);
        window.location.href="http://www.yingla9.com/dist/#/";
      }
      let text ="http://www.yingla9.com/dist/#/?uid="+window.localStorage.getItem("uid");
      global.wxShare("http://www.yingla9.com/dist/#/", "英拉助手",text, this);
      let url = global.apiUrl;
      uid = global.getCookie("uid")
      this.$http.get(url + '/shoppingCart/shoppingCartList', {
        params: {
          uid: uid,
        },
      }).then(res => {
        console.log(res);
        if (res.data.code == 0) {
          this.productData=res.data.data;
          console.log(res)
          let pData = this.productData;
          pData.forEach((val, i) => {
            val.status = false;
          })
          console.log(this.productData)
        }
      }).catch(function (err) {
        console.error(err);
      });
    }


  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
  .cart-box {
    position:absolute;
    top:0;
    left:0;
    width: 100%;
    min-height:100%;
    padding-bottom: 108px;
    background: #f3f3f3;
    /*购物车空*/
    .is-empty-box {
      width: 100%;
      text-align: center;
      padding: 30%;
      box-sizing: border-box;
      img {
        width: 60%;
      }
      p {
        margin: 0 auto;
        font-size: 1.1rem;
        color: #fff;
        margin-top: 50px;
        background: #D44242;
        padding: 5px 20px;
        border-radius: 30px;
      }
    }
    /*购物车非空*/
    .no-empty-box {
      width: 100%;
      padding: 10px 10px 0;
      li {
        width: 100%;
        height: 110px;
        margin-bottom: 10px;
        padding: 10px 0;
        background: #fff;
        border-radius: 6px;
        display: flex;
        .fl-left {
          width: 40%;
          padding: 0px 5px;
          img {
            vertical-align: middle;
          }
          .status-img {
            width: 20px;
          }
          .product-img {
            width: 77%;
            height: 95%;
          }
        }
        .fl-right {
          width: 60%;
          padding: 0 2%;
          font-size: 0.9rem;
          .title-name {
            line-height: 0.9rem;
          }
          .discription {
            width: 100%;
            height: 2rem;
            font-size: 0.7rem;
            color: #aaa;
          }
          .price-box {
            width: 100%;
            display: flex;
            justify-content: space-between;
            margin-top: 10px;
            .pb-left {
              font-size: 0.9rem;
              color: #ff0000;
            }
            .pb-right {
              img {
                width: 20px;
                vertical-align: middle;
              }
              input {
                width: 24px;
                vertical-align: middle;
                border: none;
                outline: none;
                text-align: center;
                padding: 0 4px;
              }
            }
          }
        }
      }
    }
  }

  /*底部footer*/
  .footer {
    position: fixed;
    bottom:52px;
    left:0;
    width: 100%;
    line-height: 30px;
    padding: 10px 10px;
    display: flex;
    font-size: 1rem;
    background: #fff;
    .f-all {
      margin-right: 5%;
      white-space: nowrap;
      img {
        width: 20px;
        vertical-align: middle;
      }
      span {
        vertical-align: middle;
        color: #666;
      }
    }
    .f-delete, .f-selttlement {
      width: 30%;
      text-align: center;
      border-radius: 30px;
      background: #FBB861;
      color: #fff;
      span{
        vertical-align: middle;
      }
    }
    .f-delete{
      margin-left:9%;
    }
    .f-selttlement {
      margin-left: 5%;
      background: #D85252;
    }
  }

</style>
